import { computed } from 'vue';

export default (props: any) => {
    const { ujt } = props;
    const { $fn, $db, $global } = props.ujt;

    const { initToken, userLoginWs, getOnline } = $fn.useInitUser(
        ujt,
        'webserver'
    );

    const cmLvList: any = computed(() => {
        const tmpList: any = Object.entries($fn.lg('channeluser.lv'));
        return tmpList.filter((el: any) => $global.user.info?.lv > el[0]);
    });

    function initUserChannel() {
        if (!$db.channeluser?.stat) {
            $db.channeluser = {
                cur: {
                    us:
                        $global.location.query?.us ||
                        $global.user?.info?.us ||
                        '',
                    pw: '',
                    pwn: '',
                    pwnn: '',
                    lv: 1,
                    msg: '',
                },
                stat: 0,
                rfdata: {
                    lang: computed(() => $global.lang.channeluser.data),
                },
            };
            $fn.initmodel('sys/channel/channeluser.json').then((res: any) => {
                Object.assign($db.channeluser, res);
                //console.log(666.80788, $db.channeluser);
                $db.channeluser.stat = 1;
            });
        }
    }
    function userRead() {
        //console.log(666.80788, $db.channeluser.cur);
        return new Promise<void>((resolve: any, reject: any) => {
            if ($db.channeluser.cur.us) {
                $fn.api['webserver']
                    .apiGet(
                        '/api/user/userinfo/select/' +
                            $db.channeluser.cur.us +
                            '/',
                        '',
                        {
                            mm: 1,
                        }
                    )
                    .then((resr: any) => {
                        if (
                            resr.data[0]?.[
                                Object.keys(
                                    $global.lang?.[$db.channeluser?.sn]?.data
                                )?.[1]
                            ]
                        ) {
                            resolve(
                                resr.data[0]?.[
                                    Object.keys(
                                        $global.lang?.[$db.channeluser?.sn]
                                            ?.data
                                    )?.[1]
                                ]
                            );
                        } else {
                            reject();
                        }
                    })
                    .catch((errr: any) => {
                        // //console.log(666.7766, errr);
                        reject(errr);
                    });
            } else {
                reject();
            }
        });
    }

    function userReg() {
        userRead()
            .then((resr: any) => {
                //console.log(666.808, resr);
                $global.msg.fn({
                    type: 'err',
                    tit: $fn.lg('channeluser.msg.userexist', [
                        $db.channeluser.cur.us,
                    ]),
                });
            })
            .catch((_errr: any) => {
                if ($db.channeluser.cur.us && $db.channeluser.cur.pw) {
                    userInsert();
                } else {
                    $global.msg.fn({
                        type: 'err',
                        con: $fn.lg('channeluser.msg.regerr', [
                            $db.channeluser.cur.us,
                        ]),
                    });
                }
            });
    }

    function userLoginSuccess(serverUser: any) {
        if (serverUser.us) {
            $global.user.info = {
                us: serverUser.us,
                lv: serverUser.lv || 1,
            };
            initToken();

            // console.log(666.1255, $global.user.info, $fn);
            userLoginWs().then((res: any) => {
                // console.log(666.123, res);
                userLoginClientSuccess(serverUser);
            });
        }
    }

    function userLoginClientSuccess(serverUser: any) {
        $fn.As.localSet(
            'as-user-info',
            $fn.AsAES.enc($fn.As.toStr($global.user.info))
        );
        //console.log(666.608, $global.code.token, serverUser);
        $global.msg.fn({
            type: 'ok',
            con: $fn.lg('channeluser.msg.loginok', [$global.user?.info?.us]),
        });
        $fn.sethash('');
    }

    function userLogin() {
        userRead()
            .then((resr: any) => {
                const serverUser: any = JSON.parse(resr);
                // console.log(666.111,serverUser)
                if ($db.channeluser.cur.pw === serverUser.pw) {
                    userLoginSuccess(serverUser);
                } else {
                    $global.msg.fn({
                        type: 'err',
                        tit: $fn.lg('channeluser.msg.passworderr'),
                    });
                }
            })
            .catch((errr: any) => {
                $global.msg.fn({
                    type: 'err',
                    con: $fn.lg('channeluser.msg.loginerr', [
                        $db.channeluser.cur.us,
                    ]),
                });
            });
    }

    function userExit() {
        $fn.exit();
        // 1s后跳转到首页，并刷新
        setTimeout(() => {
            $fn.sethash('');
            $fn.As.localReload();
        }, 1000);
    }

    function userEditSuccess(serverUser: any) {
        serverUser.pw = $db.channeluser.cur.pwn;
        return $fn.api['webserver']
            .apiPost(
                '/api/user/userinfo/update/' + serverUser.us + '/',
                {
                    us: serverUser.us,
                    pw: serverUser.pw,
                    lv: serverUser.lv,
                },
                {
                    mm: 1,
                }
            )
            .then((resr: any) => {
                //console.log(666.201, resr);
                $global.msg.fn({
                    type: 'ok',
                    con: $fn.lg('channeluser.msg.editok', [serverUser.us]),
                });
            })
            .catch((errr: any) => {
                $global.msg.fn({
                    type: 'err',
                    con: $fn.lg('channeluser.msg.editerr', [serverUser.us]),
                });
            });
    }

    function userEdit() {
        if (
            $db.channeluser.cur.pwn &&
            $db.channeluser.cur.pwn === $db.channeluser.cur.pwnn
        ) {
            userRead()
                .then((resr: any) => {
                    const serverUser: any = JSON.parse(resr);
                    if ($db.channeluser.cur.pw === serverUser.pw) {
                        serverUser.pw = $db.channeluser.cur.pwn; // 更新密码
                        userEditSuccess(serverUser);
                    } else {
                        $global.msg.fn({
                            type: 'err',
                            tit: $fn.lg('channeluser.msg.passworderr'),
                        });
                    }
                })
                .catch((errr: any) => {
                    //console.log(666.605, errr);
                    $global.msg.fn({
                        type: 'err',
                        con: $fn.lg('channeluser.msg.nouser', [
                            $db.channeluser.cur.us,
                        ]),
                    });
                });
        } else {
            $global.msg.fn({
                type: 'err',
                con: $fn.lg('channeluser.msg.passwordtips'),
            });
        }
    }

    function fetchContent(pctype: number = 1, svty: number = 0) {
        $fn.api['webserver']
            .apiGet('/api/user/userinfo/selectlist/', {
                svty,
                fd: 'us-lv',
                ps: $db.channeluser.cmPageSize,
                ...$global.location?.query,
            })
            .then((res: any) => {
                $db.channeluser.list = res.data;
                fetchContentCount(pctype);
            });
    }
    function fetchContentCount(pctype: number = 1) {
        if (+pctype == 0) {
            $fn.api['webserver']
                .apiGet('/api/user/userinfo/selectlist/', {
                    fd: 'us',
                    ...$global.location?.query,
                    sx: '',
                    sxty: '',
                    pc: 0,
                    pg: 0,
                    ps: Number($db.channeluser.config?.pmax) || 10000,
                })
                .then((res: any) => {
                    // //console.log(666.10022, res);
                    $fn.setquery({ pc: res.data?.length }, 1);
                    // setPage($global.location.query?.pg || 1);
                });
        }
    }

    function setPage(page: number) {
        $fn.setquery({ pg: page || 1 }, 1);
        fetchContent($global.location.query?.pc || 0);
    }

    function editUser() {
        return $fn.api['webserver']
            .apiPost(
                '/api/user/userinfo/update/' + $db.channeluser.cur.us + '/',
                {
                    us: $db.channeluser.cur.us,
                    pw: $db.channeluser.cur.pw,
                    lv: $db.channeluser.cur.lv,
                },
                { mm: 1 }
            )
            .then((resr: any) => {
                $global.msg.fn({
                    type: 'ok',
                    con: $fn.lg('channeluser.msg.editok', [
                        $db.channeluser.cur.us,
                    ]),
                });
                fetchContent(1, 0);
                $global.pop['popedituser'].stat = 0;
            })
            .catch((errr: any) => {
                //console.log(666.203, errr);
                $global.msg.fn({
                    type: 'err',
                    con: $fn.lg('channeluser.msg.editerr', [
                        $db.channeluser.cur.us,
                    ]),
                });
            });
    }

    function initUser() {
        userRead()
            .then((resr: any) => {
                if (resr) {
                    if (typeof resr === 'string') {
                        resr = JSON.parse(resr);
                    }
                    $db.channeluser.cur.us = resr.us;
                    $db.channeluser.cur.pw = resr.pw;
                    $db.channeluser.cur.lv = resr.lv || 1;
                }
            })
            .catch((_errr: any) => {
                $global.msg.fn({
                    type: 'err',
                    tit: $fn.lg('channeluser.msg.nouser', [
                        $db.channeluser.cur.us,
                    ]),
                });
            });
    }

    function delUserWork() {
        return $fn.api['webserver']
            .apiGet('/api/user/userinfo/delete/' + $db.channeluser.cur.us + '/')
            .then((resr: any) => {
                //console.log(666.201, resr);
                $global.msg.fn({
                    type: 'ok',
                    tit: $fn.lg('channeluser.msg.delok', [
                        $db.channeluser.cur.us,
                    ]),
                });
                fetchContent(0, 1);
            })
            .catch((errr: any) => {
                $db.channeluser.cur.msg = $fn.lg('channeluser.msg.delerr', [
                    $db.channeluser.cur.us,
                ]);
                //console.log(666.203, errr);
                $global.msg.fn({
                    type: 'err',
                    tit: $db.channeluser.cur.msg,
                });
            });
    }

    function delUser(userid: string = '') {
        if (userid) {
            $db.channeluser.cur.us = userid;
        }
        userRead()
            .then((resr: any) => {
                if (resr) {
                    if (typeof resr === 'string') {
                        resr = JSON.parse(resr);
                    }
                    // 不能删除等级高的、不能删除自己
                    if (
                        $global.user.info.lv > resr.lv &&
                        $global.user.info.us != resr.us
                    ) {
                        delUserWork();
                    } else {
                        $db.channeluser.cur.msg = $fn.lg(
                            'channeluser.msg.delerr',
                            [$db.channeluser.cur.us]
                        );
                        //console.log(666.301, $db.channeluser.cur.msg + resr.lv);
                        $global.msg.fn({
                            type: 'err',
                            tit: $db.channeluser.cur.msg,
                        });
                    }
                }
            })
            .catch((_errr: any) => {
                //console.log(666.303, $db.channeluser.cur.msg);
                $global.msg.fn({
                    type: 'err',
                    tit: $fn.lg('channeluser.msg.delerr', [
                        $db.channeluser.cur.us,
                    ]),
                });
            });
    }

    function userInsert() {
        return $fn.api['webserver']
            .apiPost(
                '/api/user/userinfo/insert/' + $db.channeluser.cur.us + '/',
                {
                    us: $db.channeluser.cur.us,
                    pw: $db.channeluser.cur.pw,
                    lv: $db.channeluser.cur.lv,
                }
            )
            .then((resr: any) => {
                //console.log(666.201, resr);
                $global.msg.fn({
                    type: 'ok',
                    con: $fn.lg('channeluser.msg.regok', [
                        $db.channeluser.cur.us,
                    ]),
                });
                fetchContent(0, 1);
            })
            .catch((errr: any) => {
                //console.log(666.203, errr);
                $global.msg.fn({
                    type: 'err',
                    tit: $fn.lg('channeluser.msg.regerr', [
                        $db.channeluser.cur.us,
                    ]),
                });
            });
    }

    function addUser() {
        userRead()
            .then((resr: any) => {
                //console.log(666.808, resr);
                $global.msg.fn({
                    type: 'err',
                    tit: $fn.lg('channeluser.msg.userexist', [
                        $db.channeluser.cur.us,
                    ]),
                });
            })
            .catch((_errr: any) => {
                userInsert();
                $global.pop['popadduser'].stat = 0;
            });
    }
    return {
        initUserChannel,
        userReg,
        userLogin,
        userExit,
        userEdit,
        fetchContent,
        getOnline,
        editUser,
        initUser,
        delUser,
        addUser,
        setPage,
        cmLvList,
        userLoginWs,
    };
};
